import threading
import time
from datetime import datetime
from collections import defaultdict

class DataMonitor:
    def __init__(self, log_interval=300):  # 默认5分钟输出一次日志
        self.stats = defaultdict(int)  # 统计计数器
        self.log_interval = log_interval  # 日志间隔（秒）
        self.running = False  # 控制线程
        self.thread = None
        self._start_time = datetime.now()  # 启动时间

    def start(self):
        """启动监控线程"""
        if not self.running:
            self.running = True
            self.thread = threading.Thread(target=self._run, daemon=True)
            self.thread.start()
            print(f"监控启动了，每{self.log_interval//60}分钟输出一次日志")

    def stop(self):
        """停止监控线程"""
        if self.running and self.thread:
            self.running = False
            self.thread.join(timeout=5)
            print("监控停了")

    def update(self, event_type):
        """更新统计（比如“data_received”“parse_success”）"""
        with threading.Lock():  # 多线程安全
            self.stats[event_type] += 1

    def _run(self):
        """定时输出日志"""
        while self.running:
            # 计算运行时间
            run_min = (datetime.now() - self._start_time).total_seconds() // 60
            # 输出统计
            print("\n" + "="*50)
            print(f"=== 监控日志（运行了{run_min}分钟）===")
            print(f"接收数据：{self.stats.get('data_received', 0)}条")
            print(f"解析成功：{self.stats.get('parse_success', 0)}条")
            print(f"解析失败：{self.stats.get('parse_fail', 0)}条")
            print(f"缓存数据：{self.stats.get('cache_added', 0)}条")
            print(f"转发成功：{self.stats.get('forward_success', 0)}条")
            print(f"解析成功率：{self._rate('parse_success', 'data_received'):.2%}")
            print(f"转发成功率：{self._rate('forward_success', 'cache_added'):.2%}")
            print("="*50 + "\n")

            time.sleep(self.log_interval)

    def _rate(self, success_key, total_key):
        """计算成功率，避免除零"""
        total = self.stats.get(total_key, 0)
        return self.stats.get(success_key, 0) / total if total > 0 else 0

# 本地测试
if __name__ == "__main__":
    try:
        monitor = DataMonitor(log_interval=10)  # 测试用10秒输出一次
        monitor.start()

        # 模拟数据处理，每3秒更新一次统计
        events = ["data_received", "parse_success", "cache_added", "forward_success"]
        for i in range(5):  # 循环5次
            for event in events:
                monitor.update(event)
            time.sleep(3)

        monitor.stop()
    except Exception as e:
        print("测试出错：", e)